import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { type UserVO } from '@/api-client'

export const useUserStore = defineStore('user', () => {
  const loginUser = ref<UserVO | null>(null)

  const isLogin = computed(() => !!loginUser.value?.id)

  const setUser = (user: UserVO | null) => {
    loginUser.value = user
    saveUserToStorage(user)
  }

  // 初始化时尝试从localStorage恢复用户信息
  const initUserFromStorage = () => {
    try {
      const storedUser = localStorage.getItem('loginUser')
      if (storedUser) {
        loginUser.value = JSON.parse(storedUser)
      }
    } catch (error) {
      console.error('恢复用户信息失败:', error)
      localStorage.removeItem('loginUser')
    }
  }

  // 保存用户信息到localStorage
  const saveUserToStorage = (user: UserVO | null) => {
    if (user) {
      localStorage.setItem('loginUser', JSON.stringify(user))
      if (user.token) {
        localStorage.setItem('token', user.token)
      }
    } else {
      localStorage.removeItem('loginUser')
      localStorage.removeItem('token')
    }
  }

  //保存用户token到localStorage
  const saveTokenToStorage = (token: string | null) => {
    if (token) {
      localStorage.setItem('token', token)
    }
  }

  // 清除用户信息
  const clearUser = () => {
    loginUser.value = null
    localStorage.removeItem('token')
    saveUserToStorage(null)
  }

  const logout = () => {
    clearUser()
  }

  // 初始化store时恢复用户信息
  initUserFromStorage()

  return {
    loginUser,
    saveUserToStorage,
    initUserFromStorage,
    clearUser,
    isLogin,
    setUser,
    logout,
    saveTokenToStorage,
  }
})
